from rest_framework.exceptions import ValidationError
from rest_framework.serializers import ModelSerializer
from app01.models import Group, Users, Chat, Friendship, Groupname

import base64, json, hashlib


def Base64Up(data):
    userinfo_str = json.dumps(data)
    res = base64.b64encode(userinfo_str.encode(encoding='utf-8'))
    return res


dict = {
    "address": "上海",
    "Host": "127.0.0.1"
}


def jwt_token(data):
    # 头
    headers_base64 = Base64Up(dict).decode()
    # 体
    payload = Base64Up(data).decode()
    # 签名
    secret_key = headers_base64 + payload
    secret_key = hashlib.md5(secret_key.encode()).hexdigest()
    return f'{str(headers_base64)}.{payload}.{secret_key}'


class Userserializers(ModelSerializer):
    class Meta:
        model = Users
        fields = '__all__'

    def validate(self, attrs):
        token = jwt_token(attrs)
        attrs['token'] = token
        return attrs

    def create(self, validated_data):
        username = validated_data.pop('username')
        password = validated_data.pop('password')
        user = Users.objects.create(username=username, password=password)
        return user


class Friendshipserializers(ModelSerializer):
    class Meta:
        model = Friendship
        fields = '__all__'
        extra_kwargs = {
            'is_requested': {'required': False},
            'is_accepted': {'required': False},
        }

    def create(self, validated_data):
        users_b = validated_data.pop('users_a')
        users_a = validated_data.pop('users_b')
        if Friendship.objects.filter(users_a=users_b, users_b=users_a).first() or Friendship.objects.filter(
                users_a=users_a, users_b=users_b).first():
            raise ValidationError('已申请')
        friendship = Friendship.objects.create(users_a=users_b, users_b=users_a, is_requested=True)
        return friendship

    def update(self, instance, validated_data):
        users_a = validated_data.pop('users_a')
        users_b = validated_data.pop('users_b')
        instance = Friendship.objects.get(users_a=users_a, users_b=users_b)
        instance.is_accepted = True
        instance.save()
        return instance


class Chatserializers(ModelSerializer):
    class Meta:
        model = Chat
        fields = '__all__'


class Usererializers(ModelSerializer):
    class Meta:
        model = Users
        fields = ['username']


class Groupserializers(ModelSerializer):
    user = Usererializers(many=True)
    chat = Chatserializers()

    class Meta:
        model = Group
        fields = ['groupname', 'user', 'Singlechat', 'chat']


class Groupnameserializers(ModelSerializer):
    class Meta:
        model = Group
        fields = ['groupname']


class Groupsserializers(ModelSerializer):
    class Meta:
        model = Groupname
        fields = '__all__'
